<html>
	<head>
		<title>Create user</title>
	</head>
	<body>
		<?php

		function rand_string($length) {
			$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			$size = strlen( $chars );
			$str = '';
			for( $i = 0; $i < $length; $i++ ) {
				$str .= $chars[ rand( 0, $size - 1 ) ];
			}

			return '$6$'.str_shuffle($str);
		}

		include("connectDB.php");
		//This code runs if the form has been submitted
		if (isset($_POST['submit'])) {

			if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
				die('Please fill in all of the required fields. <br/> Click <a href=createuser.php>here</a> to retry.');
			}

			if ($_POST['pass'] != $_POST['pass2']) {
				die('Your passwords did not match. <br/> Click <a href=createuser.php>here</a> to retry.');
			}

			// checks if the username is in use
			$newuser = $_POST['username'];
			$result = mysql_query("SELECT username FROM users WHERE username = '$newuser'") or die(mysql_error());
			$nRow = mysql_num_rows($result);
			//if the name exists it gives an error
			if ($nRow != 0) {
				die ('Sorry, the username '.$_POST['username'].' is already in use.');
				header("Refresh: 3; url = createuser.php");
			}

			// encrypt the password and add slashes if needed
			$salt = rand_string(10);
			
			$_POST['pass'] = crypt($_POST['pass'], $salt);
			//die($_POST['pass']);
			$_POST['pass'] = addslashes($_POST['pass']);
			$_POST['username'] = addslashes($_POST['username']);

			// add to database (default user type: user)
			$sql = "INSERT INTO users (username, password, isAdmin, salt)
			VALUES ('".$_POST['username']."', '".$_POST['pass']."', '0','".$salt."')";
			//die ($sql);
			$result = mysql_query($sql) or die(mysql_error());
			//echo $result;
			?>

			<h1>Registered</h1>
		<p>Congratulations! You have registered successfully. </a>.</p>
		<p>Click <a href=login.php>here</a> to login. </a>.</p>

			<?php
		}
		else
		{
			?>
			<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
				<table border="0">
					<tr>
						<td colspan=2>
							<h1>User Registration</h1>
						</td>
					</tr>
					<tr>
						<td>Username:</td>
						<td>
							<input type="text" name="username" maxlength="60">
						</td>
					</tr>
					<tr>
						<td>Password:</td>
						<td>
							<input type="password" name="pass" maxlength="10">
						</td>
					</tr>
					<tr>
						<td>Confirm Password:</td>
						<td>
							<input type="password" name="pass2" maxlength="10">
						</td>
					</tr>
					<tr>
						<th colspan=2>
							<input type="submit" name="submit"
							value="Register">
						</th>
					</tr>
				</table>
			</form>
			<?php
		}
		?>
	</body>
</html>
